<?php
/**
 * $Author: BEESSHOP $
 * ============================================================================
 * ============================================================================
 */
namespace app\usermodule\controllers;

use app\models\VipmemberRecorder;
use app\models\ViporderRecorder;
use app\models\VipRecorder;

class VipController extends BaseController{

    public function actionList(){
        $list = VipRecorder::find()->orderBy('vip_reduce DESC')->asArray()->all();
        $arr = [];
        foreach($list as $k=>$v){
            $arr[$k]['vip_name'] = $v['vip_name'];
            $arr[$k]['vip_reduce'] = $v['vip_reduce'];
            switch($v['vip_time']){
                case 1:
                    $arr[$k]['vip_time'] = "1个月";
                    break;
                case 2:
                    $arr[$k]['vip_time'] = "3个月";
                    break;
                case 3:
                    $arr[$k]['vip_time'] = "6个月";
                    break;
                case 4:
                    $arr[$k]['vip_time'] = "1年";
                    break;
                default:
                    $arr[$k]['vip_time']="永久";
            }
            $arr[$k]['vip_xf_num'] = $v['vip_xf_num'];
            $arr[$k]['vip_add_count'] = $v['vip_add_count'];
            $arr[$k]['vip_add_send'] = $v['vip_add_send'];
            $arr[$k]['id'] = $v['id'];
//            $vip_arr = json_decode($v['vip_type'],true);
//            $vip_string="充值".$v['vip_add_count']."元";
//            if(in_array("1",$vip_arr)){
//                $vip_string.= "充值".$v['vip_add_count']."元";
//                $vip_string.=(count($vip_arr)>=2)?"或":"";
//            }
//            if(in_array("2",$vip_arr)){
//                $vip_string.= "消费".$v['vip_xf_num']."元";
//            }
            $arr[$k]['vip_info'] = "充值".$v['vip_add_count']."元";
        }
        $result = ['result'=>1,'data'=>$arr];
        return json_encode($result);
    }


    public function actionPay(){
        $id = \Yii::$app->request->post('id');
        $model = VipRecorder::find()->where('id=:id',[':id' => $id])->one();
        if(!$model){
            $result = ['result'=>0,'data'=>'不存在相关内容，请重新操作'];
            return json_encode($result);
        }
        $price = $model->vip_add_count;
        //生成订单
        $sql = \Yii::$app->db->beginTransaction();
        try{
            $order = new ViporderRecorder();
            $order->order_name = "PAY".date('YmdHis',time()).rand(10,1000);
            $order->addtime = time();
            $order->user_id = $this->user->id;
            $order->price = $price;
            $order->vip_id = $model->id;
            $order->save(false);
            $sql->commit();
        }catch (\Exception $e){
            var_dump($e);
            $sql->rollBack();
            $result = ['result'=>0,'data'=>'支付订单创建失败，请重新操作'];
            return json_encode($result);
        }

        $body=[
            "appid"=>\Yii::$app->params['appid'],
            "mch_id"=>\Yii::$app->params['sh_id'],
            "nonce_str"=>\Yii::$app->security->generateRandomString(),
            "body"=>\Yii::$app->params['base_url']."会员升级充值",
            "out_trade_no"=>$order->order_name,
            "total_fee" => intval($price*100),
            "spbill_create_ip"=>$_SERVER['REMOTE_ADDR'],
            "notify_url"=>"https://www.weixin.qq.com/wxpay/pay.php",
            "trade_type"=>"JSAPI",
            "openid"=>$this->user->openid,
        ];
        $data = $this->pay($body);
        $result = ['result'=>1,'data'=>$data,"order_id"=>$order->id];
        return json_encode($result);
    }

    public function pay($body){
        ksort($body);
        $xml="<xml>";
        $sign="";
        foreach($body as $k=>$v){
            $xml.="<{$k}>{$v}</{$k}>";
            $sign.="{$k}={$v}&";
        }
        $sign.="key=".\Yii::$app->params['sh_key'];
        $sign = strtoupper(md5($sign));
        $xml.="<sign>{$sign}</sign></xml>";
        $url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$xml);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,1);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        $res = curl_exec($ch);
        curl_close($ch);
        $res = simplexml_load_string($res,"SimpleXMLElement",LIBXML_NOCDATA);
        $res = json_decode(json_encode($res),true);
        $return_arr=[
            "appId"=>\Yii::$app->params['appid'],
            "timeStamp"=>time(),
            "nonceStr"=>\Yii::$app->security->generateRandomString(),
            "package"=>"prepay_id=".$res['prepay_id'],
            "signType"=>"MD5",
        ];
        ksort($return_arr);
        $paySign="";
        foreach($return_arr as $k=>$v){
            $paySign.="{$k}={$v}&";
        }
        $paySign .= "key=".\Yii::$app->params['sh_key'];
        $return_arr['paySign']=strtoupper(md5($paySign));
        return $return_arr;
    }


    public function actionWxpay(){
        $id = \Yii::$app->request->post('id');
        $order = ViporderRecorder::find()->where('id=:id',[':id' => $id])->andWhere('user_id='.$this->user->id)->one();
        if(empty($order)){
            $result = ['result'=>0,'data'=>'不存在相关订单，请联系客服处理'];
            return json_encode($result);
        }
        $vip = VipRecorder::find()->where('id='.$order->vip_id)->one();
        if(empty($vip)){
            $result = ['result'=>0,'data'=>'不存在相关vip，请联系客服处理'];
            return json_encode($result);
        }
        $url="https://api.mch.weixin.qq.com/pay/orderquery";
        $body=[
            "appid"=>\Yii::$app->params['appid'],
            "mch_id"=>\Yii::$app->params['sh_id'],
            "out_trade_no"=>$order->order_name,
            "nonce_str"=>\Yii::$app->security->generateRandomString(),
        ];
        ksort($body);
        $xml="<xml>";
        $sign="";
        foreach($body as $k=>$v){
            $xml.="<{$k}>{$v}</{$k}>";
            $sign.="{$k}={$v}&";
        }
        $sign.="key=".\Yii::$app->params['sh_key'];
        $sign = strtoupper(md5($sign));
        $xml.="<sign>{$sign}</sign></xml>";
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,1);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$xml);
        $res = curl_exec($ch);
        curl_close($ch);
        $res = simplexml_load_string($res,"SimpleXMLElement",LIBXML_NOCDATA);
        $res = json_decode(json_encode($res),true);
        if($res['trade_state']=="SUCCESS"){//支付成功
            $sql=\Yii::$app->db->beginTransaction();
            try{
                $order->is_pay = 1;
                $order->save(false);
                $this->user->pay_num =$this->user->pay_num+$vip->vip_add_count+$vip->vip_add_send;
                $this->user->pay_num = sprintf("%.2f",$this->user->pay_num);
                $this->user->vip=$vip->id;
                switch ($vip->vip_time){
                    case 0:
                        $this->user->vip_time = strtotime("+ 100 years",time());
                        break;
                    case 1:
                        $this->user->vip_time = strtotime("+ 1 month",time());
                        break;
                    case 2:
                        $this->user->vip_time = strtotime("+ 3 month",time());
                        break;
                    case 3:
                        $this->user->vip_time = strtotime("+ 6 month",time());
                        break;
                    case 4:
                        $this->user->vip_time = strtotime("+ 1 years",time());
                        break;
                }
                $this->user->save(false);
                $sql->commit();
            }catch (\Exception $e){
                $sql->rollBack();
                $result = ['result'=>0,'data'=>'订单处理失败，请联系客服处理'];
                return json_encode($result);
            }
            $result = ['result'=>1,'data'=>'操作成功'];
            return json_encode($result);
        }else{
            $result = ['result'=>0,'data'=>'订单未支付完成，状态：'.$res['trade_state']];
            return json_encode($result);
        }
    }


}
